import { http } from '@/common/service.js'

export function login(loginSuccess,loginFail){
	uni.showLoading({mask:true})
	uni.login({
		provider: 'weixin',
		success: function(loginRes) {
			console.log(loginRes);
			assessLogin(loginRes.code, loginSuccess, loginFail);
		},
		fail: function(err){
			console.log(err);
			utils.showToast('微信登录失败')
			uni.hideLoading()
			loginFail(res)
		}
	});
}

function assessLogin(code, loginSuccess, loginFail) {
	var url = 'wx/user/' + getApp().globalData.appid + '/login';
	http.request({
		url: url,
		data: {
			appid: getApp().globalData.appid,
			code: code,
		},
	}).then(res => {
		console.log(res);
		uni.hideLoading();
		if (res.code === "000000") {
			try {
				uni.setStorageSync('token', res.data.ticket);
				uni.setStorageSync('user',res.data.user);
				uni.setStorageSync('session',res.data.session);
			} catch (e) {}
			getApp().globalData.user = res.data.user;
			getApp().globalData.ticket = res.data.ticket;
			getApp().globalData.session = res.data.session;
			loginSuccess(res);
		} else {
			loginFail(res);
			uni.showToast({
				title: '登录出错:'+res.msg,
				icon:'none'
			})
		}
	}).catch(err => {
		console.log(err);
		loginFail(err);
		utils.showToast(err);
		uni.hideLoading();
	});
}


module.exports = {
	login: login,
}
